
import java.awt.Color;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

import java.util.*;

public class XYChart extends ApplicationFrame{
	
	static final long serialVersionUID = 1l;
	
	/**
	 * Constructor
	 * @param title graph title
	 * @param bestFitness list of best chromosome fitness over generations
	 * @param avgFitness list of average chromosome fitness over generations
	 */
	public XYChart(final String title, List<Double> bestFitness, List<Double> avgFitness) {
	    super(title);
	
	    // prepare given data to chart format
	    final XYSeries bestSeries= new XYSeries("Best Chromosome");
	    final XYSeries avgSeries = new XYSeries("Average Chromosome");

	    int limit = bestFitness.size();
	    
	    Iterator<Double> bestItr = bestFitness.iterator();
	    Iterator<Double> avgItr = avgFitness.iterator();
	    	    
	    for (int i = 0; i < limit; ++i) {
	    	bestSeries.add(i, bestItr.next());
	    	avgSeries.add(i, avgItr.next());
	    }
	    	
	    // create chart
	    final XYSeriesCollection dataset = new XYSeriesCollection();
	    dataset.addSeries(bestSeries);
	    dataset.addSeries(avgSeries);
	
	    final JFreeChart chart = ChartFactory.createXYLineChart(
	        title,          // chart title
	        "Generation",               // domain axis label
	        "Fitness",                  // range axis label
	        dataset,                  // data
	        PlotOrientation.VERTICAL,
	        true,                     // include legend
	        true,
	        false
	    );
	
	    final XYPlot plot = chart.getXYPlot();
	    final NumberAxis domainAxis = new NumberAxis("Generation");
	    final NumberAxis rangeAxis = new NumberAxis("Fitness");
	    
	    rangeAxis.setRange(Math.min(bestSeries.getMinY(), avgSeries.getMinY() - 10), 
	    					Math.max(bestSeries.getMaxY(), avgSeries.getMaxY()) + 30);
	    plot.setDomainAxis(domainAxis);
	    plot.setRangeAxis(rangeAxis);
	    
	    chart.setBackgroundPaint(Color.white);
	    plot.setOutlinePaint(Color.black);
	    
	    final ChartPanel chartPanel = new ChartPanel(chart);
	    chartPanel.setPreferredSize(new java.awt.Dimension(800, 570));
	    setContentPane(chartPanel);
	}
	
}
